/*
 * @Author: Drc
 * @Date: 2021-07-05 17:03:39
 * @LastEditTime: 2021-12-30 15:13:16
 * @LastEditors: Drc
 */
/**
 * 运算
 */
class Operation {
  //精度加法
  static plus(arg1: number, arg2: number) {
    if (isNaN(Number(arg1)) || isNaN(Number(arg2))) {
      return
    }
    var r1, r2, m
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
  }

  //精度减法
  static subtract(arg1: number, arg2: number) {
    if (isNaN(Number(arg1)) || isNaN(Number(arg2))) {
      return
    }
    var r1, r2, m, n
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    n = r1 >= r2 ? r1 : r2
    return ((arg1 * m - arg2 * m) / m).toFixed(n)
  }

  //精度乘法
  static multiply(arg1: number, arg2: number) {
    if (isNaN(Number(arg1)) || isNaN(Number(arg2))) {
      return
    }
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString()
    try {
      m += s1.split('.')[1].length
    } catch (e) {}
    try {
      m += s2.split('.')[1].length
    } catch (e) {}
    return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
  }

  //精度除法
  static divide(arg1: number, arg2: number) {
    if (isNaN(Number(arg1)) || isNaN(Number(arg2))) {
      return
    }
    var t1 = 0,
      t2 = 0,
      r1,
      r2
    try {
      t1 = arg1.toString().split('.')[1].length
    } catch (e) {}
    try {
      t2 = arg2.toString().split('.')[1].length
    } catch (e) {}
    while (Math) {
      r1 = Number(arg1.toString().replace('.', ''))
      r2 = Number(arg2.toString().replace('.', ''))
      return (r1 / r2) * Math.pow(10, t2 - t1)
    }
  }

  //往上截取小数
  static ceilFixed = (num: number, digit: number) => {
    try {
      num = Number(num)
      if (isNaN(num)) {
        return num
      }
      let result = this.multiply(num, Math.pow(10, digit))
      result = Math.ceil(result)
      result = this.divide(result, Math.pow(10, digit))?.toFixed(digit)
      return result
    } catch (error) {
      return num
    }
  }

  //往下截取小数
  static floorFixed = (num: number, digit: number) => {
    try {
      num = Number(num)
      if (isNaN(num)) {
        return num
      }
      let result = this.multiply(num, Math.pow(10, digit))
      result = Math.floor(result)
      result = this.divide(result, Math.pow(10, digit))?.toFixed(digit)
      return result
    } catch (error) {
      return num
    }
  }
}

export default Operation
